/**
 * 工程名称:OMSJobExecutor
 * 文件名称:SysRefundController.java
 * 所属包:cn.rkylin.oms.sysrefund.controller
 * 创建时间:2017年9月21日下午2:54:30
 * 创建人:zhanghao
 */

package cn.rkylin.oms.aftersale.sysrefund.controller;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;

import cn.rkylin.core.controller.ApolloController;
import cn.rkylin.oms.aftersale.sysrefund.dao.ISysRefundDAO;
import cn.rkylin.oms.aftersale.sysrefund.domain.SysRefund;
import cn.rkylin.oms.aftersale.sysrefund.domain.SysRefundSku;
import cn.rkylin.oms.aftersale.sysrefund.servcie.ISysRefundService;
import cn.rkylin.oms.aftersale.sysrefund.vo.SysRefundSkuVO;
import cn.rkylin.oms.aftersale.sysrefund.vo.SysRefundVO;
import cn.rkylin.oms.common.annotation.SystemControllerLog;
import cn.rkylin.oms.common.context.CurrentUser;
import cn.rkylin.oms.common.context.WebContextFactory;
import cn.rkylin.oms.common.dto.DBLog;
import cn.rkylin.oms.common.utils.LogUtil;
import cn.rkylin.oms.order.service.IOrderService;
import cn.rkylin.oms.order.vo.OrderSkuVO;
import cn.rkylin.oms.system.log.dao.ILogDao;
import cn.rkylin.oms.system.shop.service.IShopService;
import cn.rkylin.oms.system.shop.vo.ShopVO;

/**
 * 类名:SysRefundController <br/>
 * 作用: 系统退款单操作Controller. <br/>
 * 创建原因: 对外提供系统退款单相关操作. <br/>
 * 创建时间: 2017年9月21日 下午2:54:30 <br/>
 * 
 * @author zhanghao
 * @see
 */
@Controller
@RequestMapping("/sysRefundManager")
public class SysRefundController extends ApolloController {
    private static final String DOWNLOAD_EXCEPTION_MSG = "退款单手动下载失败，请联系系统管理员";

    private static final String DOWNLOAD_SUCCESS_MSG = "下载成功";

    private static final Log logger = LogFactory.getLog(SysRefundController.class);

    /**
     * sysRefundService:系统退款单服务层.
     */
    @Autowired
    private ISysRefundService sysRefundService;
    @Autowired
    private IOrderService orderService;
    @Autowired
    private IShopService shopService;
    @Autowired
    private LogUtil logUtil;
	@Autowired
	private ILogDao logDao;

    /**
     * generateSysRefund:平台退款单进系统. <br/>
     * 系统定时调用.<br/>
     * 系统获取一定条件下的平台退款单，自动生成系统退款单.<br/>
     * 系统定时调用.<br/>
     * 此方法的业务逻辑较复杂，数据库操作较多，建议不要在循环中调用.<br/>
     *
     * @author zhanghao
     * @param paramMap
     *            控制参数Map
     * @return 执行成功或者失败的消息
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/autoGenerateSysRefund")
    @SystemControllerLog(module = "系统退款单", operation = "平台退款单进系统", keyCode = "shopId")
    public Map<String, Object> autoGenerateSysRefund(@RequestParam(value = "shopId") String shopId, Map paramMap) {
        logger.info(String.format("系统调用自动下载退款单：/sysRefundManager/autoGenerateSysRefund/%s", shopId));
        // 用于返回值的json对象
        Map<String, Object> returnMap = new HashMap<String, Object>();
        String shopName = "";
    	CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
        try {
            ShopVO shopVO = shopService.getShopById(shopId);
            shopName = shopVO.getShopName();
            sysRefundService.downloadEcRefundAuto(shopId);
            returnMap = getSuccessMap("系统调用完成");
            logUtil.trace(new DBLog(shopName, "系统退款单自动进系统", "系统退款单", "退款单自动下载完成"),logDao,currentUser.getFullName());
        } catch (Exception e) {
            logUtil.trace(new DBLog(shopName, "系统退款单自动进系统", "系统退款单", "退款单自动下载失败"),logDao,currentUser.getFullName());
        }
        returnMap.put("shopId", shopId);
        return returnMap;
    }

    /**
     * sysRefundDetail:根据退款单ID获取系统退款单详情. <br/>
     *
     * @author zhanghao
     * @param sysRefundId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/sysRefundDetail")
    public Map<String, Object> sysRefundDetail(@RequestParam(value = "sysRefundId") String sysRefundId) {
        logger.info(String.format("系统调用获取系统退款单明细：/sysRefundManager/sysRefundDetail/%s", sysRefundId));
        // 用于返回值的json对象
        Map<String, Object> returnMap = null;
        try {
            SysRefundVO queryParam = new SysRefundVO();
            queryParam.setRefundId(sysRefundId);
            SysRefund result = sysRefundService.getSysRefundListById(sysRefundId);
            if (null != result) {
                returnMap = getSuccessMap("系统调用完成");
                returnMap.put(RETURN_DATA, result);
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            returnMap = getFailedMap(e.getMessage());
        }
        return returnMap;
    }

    /**
     * sysRefundFullDetail:根据系统退款单ID获取系统退款单详情. <br/>
     * 包括退款单内容，退款单明细，相关退货单内容.<br/>
     *
     * @author zhanghao
     * @param sysRefundId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/sysRefundFullDetail")
    public Map<String, Object> sysRefundFullDetail(@RequestParam(value = "sysRefundId") String sysRefundId) {
        logger.info(String.format("系统调用获取系统退款单明细：/sysRefundManager/sysRefundFullDetail/%s", sysRefundId));
        // 用于返回值的json对象
        Map<String, Object> returnMap = null;
        try {
            SysRefundVO result = sysRefundService.getSysRefundDetailById(sysRefundId);
            if (null != result) {
                returnMap = getSuccessMap("系统调用完成");
                returnMap.put(RETURN_DATA, result);
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            returnMap = getFailedMap(e.getMessage());
        }
        return returnMap;
    }

    @ResponseBody
    @RequestMapping(value = "/getOrderSkuByRefundId")
    public Map<String, Object> getOrderSkuByRefundId(@RequestParam(value = "refundId") String refundId) {
        logger.info(String.format("系统调用获取系统退款单商品明细：/sysRefundManager/getOrderSkuByRefundId/%s", refundId));
        // 用于返回值的json对象
        Map<String, Object> returnMap = null;
        try {
            List<OrderSkuVO> orderSkuList = orderService.getOrderSkuByRefundId(refundId);
            List<SysRefundSkuVO> refundSkuList = new ArrayList<SysRefundSkuVO>();

            List<SysRefundSku> sysRefundSkuList = sysRefundService.getSysRefundDetailById(refundId).getSysRefundSkuList();
            Map<String, BigDecimal> refundFeeMap = new HashMap<String, BigDecimal>();

            for (int i = 0, j = sysRefundSkuList.size(); i < j; i++) {
                refundFeeMap.put(sysRefundSkuList.get(i).getSourceSkuId(), sysRefundSkuList.get(i).getRefundFee());
            }

            for (int i = 0, j = orderSkuList.size(); i < j; i++) {
                OrderSkuVO orderSku = orderSkuList.get(i);
                SysRefundSkuVO sysRefundSku = new SysRefundSkuVO();
                BeanUtils.copyProperties(orderSku, sysRefundSku);

                sysRefundSku.setRefundFee(refundFeeMap.get(sysRefundSku.getOrderSkuId()));
                refundSkuList.add(sysRefundSku);
            }
            returnMap = getSuccessMap("系统调用完成");
            returnMap.put(RETURN_DATA, refundSkuList);
        } catch (Exception e) {
            logger.error(e.getMessage());
            returnMap = getFailedMap(e.getMessage());
        }
        return returnMap;
    }

    @ResponseBody
    @RequestMapping(value = "/getOrderSkuById")
    public Map<String, Object> getOrderSkuById(@RequestParam(value = "orderId") String orderId) {
        logger.info(String.format("系统调用获取订单商品明细：/sysRefundManager/getOrderSkuById/%s", orderId));
        // 用于返回值的json对象
        Map<String, Object> returnMap = null;
        try {
            List<OrderSkuVO> orderSkuList = orderService.getAllOrderSku(orderId);
            if (orderSkuList.size() > 0) {
                returnMap = getSuccessMap("系统调用完成");
                returnMap.put(RETURN_DATA, orderSkuList);
            } else {
                returnMap = getFailedMap("系统调用完成,未获取到数据");
            }

        } catch (Exception e) {
            logger.error(e.getMessage());
            returnMap = getFailedMap(e.getMessage());
        }
        return returnMap;
    }

    @ResponseBody
    @RequestMapping(value = "/saveSysRefund", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @SystemControllerLog(module = "系统退款单", operation = "保存退款单及其明细", keyCode = "refundId")
    public Map<String, Object> saveSysRefund(@RequestBody SysRefundVO sysRefundVO) {
        // 用于返回值的json对象
        logger.info(String.format("系统调用保存退款单及其明细：/sysRefundManager/saveSysRefund"));
        Map<String, Object> returnMap = null;
        CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
        try {
            List<String> orderSkuIdList = null;
            int returnValue = sysRefundService.saveSysRefunds(sysRefundVO);
            returnMap = getSuccessMap("系统退款单保存成功");
            logger.info("系统退款单[单号：" + sysRefundVO.getRefundCode() + "]保存成功");
            logUtil.trace(new DBLog(sysRefundVO.getRefundCode(), "系统退款单保存", "系统退款单", "退款单[单号：" + sysRefundVO.getRefundCode() + "]新增或更新成功"),logDao,currentUser.getFullName());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            returnMap = getFailedMap("系统程序异常，请联系系统管理员");
            logUtil.trace(new DBLog(sysRefundVO.getRefundCode(), "系统退款单保存", "系统退款单", "系统异常" + e.getMessage()),logDao,currentUser.getFullName());
        }
        returnMap.put("refundId", sysRefundVO.getRefundId());
        return returnMap;
    }

    /**
     * generateSysRefund:平台退款单进系统. <br/>
     * 系统定时调用.<br/>
     * 系统获取一定条件下的平台退款单，自动生成系统退款单.<br/>
     * 系统定时调用.<br/>
     * 此方法的业务逻辑较复杂，数据库操作较多，建议不要在循环中调用.<br/>
     *
     * @author zhanghao
     * @param quickSearch
     *            快速查询
     * @param formJson
     * @param queryStatus
     * @return 执行成功或者失败的消息
     * @throws UnsupportedEncodingException
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/queryStateCount")
    @SystemControllerLog(module = "系统退款单", operation = "查询系统退款单")
    public Map<String, Object> queryStateCount(String quickSearch, String formJson, String queryStatus) throws UnsupportedEncodingException {
        Map returnMap = new HashMap();
        logger.info(String.format("系统调用计算系统退款单状态数字：/sysRefundManager/queryStateCount"));
        logger.info("查询系统退款单：/sysRefundManager/sysRefundList");
        SysRefundVO queryParamVO = new SysRefundVO();
        if (quickSearch != null && StringUtils.isNotEmpty(quickSearch)) {
            quickSearch = URLDecoder.decode(quickSearch, "UTF-8");
            if (StringUtils.isNotEmpty(quickSearch)) {
                queryParamVO.setQuickSearch(quickSearch);
            }
        }
        try {
            if (formJson != null && StringUtils.isNotEmpty(formJson)) {
                formJson = URLDecoder.decode(formJson, "UTF-8");
                Map<String, String> mapItem = JSONObject.parseObject(formJson, Map.class);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                if (mapItem != null && !mapItem.isEmpty()) {
                    if (StringUtils.isNotEmpty(mapItem.get("orderCode"))) {
                        queryParamVO.setQueryOrderCode(mapItem.get("orderCode"));
                    }
                    if (StringUtils.isNotEmpty(mapItem.get("shopId"))) {
                        queryParamVO.setShopId(mapItem.get("shopId"));
                    }
                    if (StringUtils.isNotEmpty(mapItem.get("dateType"))) {
                        queryParamVO.setQueryDateType(mapItem.get("dateType"));
                    }
                    if (StringUtils.isNotEmpty(mapItem.get("queryDateStart"))) {
                        queryParamVO.setQueryDateStart(sdf.parse(mapItem.get("queryDateStart")));
                    }

                    if (StringUtils.isNotEmpty(mapItem.get("queryDateEnd"))) {
                        queryParamVO.setQueryDateEnd(sdf.parse(mapItem.get("queryDateEnd")));
                    }
                    if (StringUtils.isNotEmpty(mapItem.get("ecItemCode"))) {
                        queryParamVO.setQueryEcItemCode(mapItem.get("ecItemCode"));
                    }
                    if (StringUtils.isNotEmpty(mapItem.get("ecSkuCode"))) {
                        queryParamVO.setQueryEcSkuCode(mapItem.get("ecSkuCode"));
                    }
                    if (StringUtils.isNotEmpty(mapItem.get("skuCode"))) {
                        queryParamVO.setQuerySkuCode(mapItem.get("skuCode"));
                    }
                    if (StringUtils.isNotEmpty(mapItem.get("returnDiff"))) {
                        queryParamVO.setReturnDiff(mapItem.get("returnDiff"));
                    }
                    if (StringUtils.isNotEmpty(mapItem.get("refundChannel"))) {
                        queryParamVO.setRefundChannel(mapItem.get("refundChannel"));
                    }
                }
            }
        } catch (ParseException e) {
            logger.error(e.getMessage());
            returnMap = getFailedMap("获取状态数据失败");
        }

        // 获取当前登录人
        CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
        if (currentUser == null) {
            return getFailedMap("查询当前登录人失败");
        }

        // 获取当前登录人所属项目
        String projectId = currentUser.getCurrentProject().getPrjId();
        if (StringUtils.isBlank(projectId)) {
            return getFailedMap("查询当前登录人所属项目失败");
        }
        queryParamVO.setPrjId(projectId);

        if (StringUtils.isNotEmpty(queryStatus)) {
            queryParamVO.setQueryStatus(queryStatus);
        }

        List<HashMap> stateMap = new ArrayList<HashMap>();
        try {
            stateMap = sysRefundService.findStateCount(queryParamVO);
            returnMap = getSuccessMap("完成查询系统退款单数据");
            returnMap.put(RETURN_DATA, stateMap);
        } catch (Exception e) {
            logger.error(e.getMessage());
            returnMap = getFailedMap("获取状态数据失败");
        }
        return returnMap;
    }

    /**
     * manualGenerateSysRefund:根据客户ID手动下载平台退款单，并生成系统退款单. <br/>
     * 参考自动生成系统退款单的业务逻辑.<br/>
     *
     * @author zhanghao
     * @param shopId
     *            店铺ID
     * @param customerId
     *            客户ID（顾客昵称）
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/manualGenerateSysRefundByCustomerId")
    @SystemControllerLog(module = "系统退款单", operation = "根据客户ID手动下载退款单", keyCode = "shopId")
    public Map<String, Object> manualGenerateSysRefundByCustomerId(@RequestParam(value = "shopId") String shopId,
            @RequestParam(value = "customerId") String customerId) {
        logger.debug("系统调用根据客户ID手动下载退款单：/sysRefundManager/manualGenerateSysRefundByCustomerId/" + customerId);
        Map<String, Object> returnMap = null;
        try {
            String queryParam = URLDecoder.decode(customerId, "UTF-8");
            JSONObject result = sysRefundService.downloadEcRefundByCustomerId(shopId, queryParam);
            if (SUCCESS.equals(result.getString(JSON_RESULT))) {
                returnMap = getSuccessMap(DOWNLOAD_SUCCESS_MSG);
            } else {
                returnMap = getFailedMap(result.getString(JSON_MSG));
            }
        } catch (Exception e) {

            returnMap = getFailedMap(e.getMessage());
        }
        returnMap.put("shopId", shopId);
        return returnMap;
    }

    /**
     * manualGenerateSysRefundByOrderCode:根据订单编号下载平台退款单，并生成系统退款单. <br/>
     * 参考自动生成系统退款单的业务逻辑.<br/>
     *
     * @author zhanghao
     * @param shopId
     *            店铺ID
     * @param orderCode
     *            订单编号
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/manualGenerateSysRefundByOrderCode")
    @SystemControllerLog(module = "系统退款单", operation = "根据订单编号手动下载退款单", keyCode = "shopId")
    public Map<String, Object> manualGenerateSysRefundByOrderCode(@RequestParam(value = "shopId") String shopId,
            @RequestParam(value = "orderCode") String orderCode) {
        logger.debug("系统调用根据订单号手动下载退款单：/sysRefundManager/manualGenerateSysRefundByOrderCode/" + orderCode);
        Map<String, Object> returnMap;
        try {
            String queryParam = URLDecoder.decode(orderCode, "UTF-8");
            JSONObject result = sysRefundService.downloadEcRefundByOrderCode(shopId, queryParam);
            if (SUCCESS.equals(result.getString(JSON_RESULT))) {
                returnMap = getSuccessMap(DOWNLOAD_SUCCESS_MSG);
            } else {
                returnMap = getFailedMap(result.getString(JSON_MSG));
            }
        } catch (Exception e) {
            returnMap = getFailedMap(e.getMessage());
            // returnMap = getFailedMap(DOWNLOAD_EXCEPTION_MSG);
        }
        returnMap.put("shopId", shopId);
        return returnMap;
    }

    /**
     * manualGenerateSysRefund:根据退款单号获取相关平台退款单，并生成系统退款单. <br/>
     * 参考自动生成系统退款单的业务逻辑.<br/>
     *
     * @author zhanghao
     * @param shopId
     *            店铺ID
     * @param ecRefundCode
     *            平台退款单编号
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/manualGenerateSysRefundByEcRefundCode")
    @SystemControllerLog(module = "系统退款单", operation = "根据退款单编号手动下载退款单", keyCode = "shopId")
    public Map<String, Object> manualGenerateSysRefundByEcRefundCode(@RequestParam(value = "shopId") String shopId,
            @RequestParam(value = "ecRefundCode") String ecRefundCode) {
        logger.debug("系统调用根据退款单号手动下载退款单：/sysRefundManager/manualGenerateSysRefundByOrderCode/" + ecRefundCode);
        Map<String, Object> returnMap;

        try {
            String queryParam = URLDecoder.decode(ecRefundCode, "UTF-8");
            JSONObject result = sysRefundService.downloadEcRefundByEcRefundCode(shopId, queryParam);
            if (SUCCESS.equals(result.getString(JSON_RESULT))) {
                returnMap = getSuccessMap(DOWNLOAD_SUCCESS_MSG);
            } else {
                returnMap = getFailedMap(result.getString(JSON_MSG));
            }
        } catch (Exception e) {
            // returnMap = getFailedMap(DOWNLOAD_EXCEPTION_MSG);
            returnMap = getFailedMap(e.getMessage());
        }
        returnMap.put("shopId", shopId);
        return returnMap;
    }

    /**
     * autoUpdateSysRefund:退款单更新. <br/>
     * 系统定时调用<br/>
     * 当监测到有退款单更新时，更新退款单相关信息.<br/>
     * 此方法为批量操作<br/>
     * 此方法的业务逻辑较复杂，数据库操作较多，建议不要在循环中调用.<br/>
     *
     * @author zhanghao
     * @param shopId
     * @param paramMap
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/autoUpdateSysRefund")
    @SystemControllerLog(module = "系统退款单", operation = "退款单更新", keyCode = "shopId")
    public Map<String, Object> autoUpdateSysRefund(@RequestParam(value = "shopId") String shopId, String start, String end, Map paramMap) {
        logger.info(String.format("系统调用：/sysRefundManager/autoUpdateSysRefund/%s", shopId));
        // 用于返回值的json对象
        Map<String, Object> returnMap;
        try {
            sysRefundService.updateEcRefundAuto(shopId);
            returnMap = getSuccessMap("系统调用完成");
        } catch (Exception e) {
            returnMap = getFailedMap(e.getMessage());
        }
        // 生成返回结果json串，null内容也需要返回
        returnMap.put("shopId", shopId);
        return returnMap;
    }

    /**
     * cancelSysRefund:废弃退款单. <br/>
     *
     * @author zhanghao
     * @param refundIds
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/cancelSysRefund")
    @SystemControllerLog(module = "系统退款单", operation = "废弃退款单", keyCode = "refundId")
    public Map<String, Object> cancelSysRefund(@RequestParam(value = "refundIds") String refundIds) {
        logger.info(String.format("系统调用：/sysRefundManager/cancelSysRefund/%s", refundIds));
        String[] refundIdArray = StringUtils.split(refundIds, ",");
        // 用于返回值的json对象
        Map<String, Object> returnMap = null;
        CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
        try {
            int result = sysRefundService.cancelSysRefunds(refundIdArray);
            if (result > 0) {
                returnMap = getSuccessMap("退款单已作废");
                logUtil.trace(new DBLog(refundIds, "作废退款单", "系统退款单", "退款单作废完成"),logDao,currentUser.getFullName());
            } else if (0 == result) {
                returnMap = getFailedMap("退款单[" + refundIds + "]作废失败，请刷新后重试");
                logUtil.trace(new DBLog(refundIds, "作废退款单", "系统退款单", "退款单作废失败，没有可作废的退款单"),logDao,currentUser.getFullName());
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            returnMap = getFailedMap("系统程序异常，请联系系统管理员");
            logUtil.trace(new DBLog(refundIds, "作废退款单", "系统退款单", "系统程序异常，请联系系统管理员"),logDao,currentUser.getFullName());
        }
        // 生成返回结果json串，null内容也需要返回
        returnMap.put("refundId", refundIds);
        return returnMap;
    }

    /**
     * cancelSysRefund:审核退款单. <br/>
     *
     * @author zhanghao
     * @param refundIds
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/apprSysRefund")
    @SystemControllerLog(module = "系统退款单", operation = "审核退款单", keyCode = "refundId")
    public Map<String, Object> apprSysRefund(@RequestParam(value = "refundIds") String refundIds) {
        logger.info(String.format("系统调用审核退款单：/sysRefundManager/apprSysRefund/%s", refundIds));
        String[] refundIdArray = StringUtils.split(refundIds, ",");
        JSONArray returnArray = new JSONArray();
        // 用于返回值的json对象
        Map<String, Object> returnMap = null;
        CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
        try {
            for (String sysRefundId : refundIdArray) {
                JSONObject jsonObject = sysRefundService.doAppr(sysRefundId);
                jsonObject.put("sysRefundId", sysRefundId);
                returnArray.add(jsonObject);
            }
            returnMap = getSuccessMap("审核退款单完成");
            returnMap.put("detail", returnArray);
            logUtil.trace(new DBLog(refundIds, "审核退款单", "系统退款单", "退款单审核完成"),logDao,currentUser.getFullName());
        } catch (Exception e) {
            logger.error(e.getMessage());
            returnMap = getFailedMap(e.getMessage());
            logUtil.trace(new DBLog(refundIds, "审核退款单", "系统退款单", "系统程序异常，请联系系统管理员"),logDao,currentUser.getFullName());
        }
        // 生成返回结果json串，null内容也需要返回
        returnMap.put("refundId", refundIds);
        return returnMap;
    }

    /**
     * forceApprSysRefundValid:强制审核退款单校验. <br/>
     *
     * @author zhanghao
     * @param refundId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/forceApprSysRefundValid")
    public Map<String, Object> forceApprSysRefundValid(@RequestParam(value = "refundId") String refundId) {
        logger.info(String.format("系统调用强制审核退款单校验：/sysRefundManager/forceApprSysRefund/%s", refundId));
        JSONArray returnArray = new JSONArray();
        // 用于返回值的json对象
        Map<String, Object> returnMap = null;
        CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
        try {
            JSONObject resultObject = sysRefundService.doForceApprValid(refundId);
            returnMap = getSuccessMap("强制审核校验完成");
            returnMap.put("message", resultObject);
            logUtil.trace(new DBLog(refundId, "检查退款单是否能强制审核", "系统退款单", "检查结果：" + resultObject.toJSONString()),logDao,currentUser.getFullName());
        } catch (Exception e) {
            logger.error(e.getMessage());
            returnMap = getFailedMap(e.getMessage());
            logUtil.trace(new DBLog(refundId, "检查退款单是否能强制审核", "系统退款单", "系统程序异常，请联系系统管理员"),logDao,currentUser.getFullName());
        }
        // 生成返回结果json串，null内容也需要返回
        return returnMap;
    }

    /**
     * forceApprSysRefundValid:强制审核退款单. <br/>
     *
     * @author zhanghao
     * @param refundIds
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/forceApprSysRefund")
    @SystemControllerLog(module = "系统退款单", operation = "强制审核退款单校验", keyCode = "refundId")
    public Map<String, Object> forceApprSysRefund(@RequestParam(value = "refundIds") String refundIds) {
        logger.info(String.format("系统调用强制审核退款单：/sysRefundManager/forceApprSysRefund/%s", refundIds));
        String[] refundIdArray = StringUtils.split(refundIds, ",");
        JSONArray returnArray = new JSONArray();
        // 用于返回值的json对象
        Map<String, Object> returnMap = null;
        CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
        try {
            for (String sysRefundId : refundIdArray) {
                String result = sysRefundService.doForceAppr(sysRefundId);
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("refundId", sysRefundId);
                jsonObject.put("message", result);
                returnArray.add(jsonObject);
            }
            returnMap = getSuccessMap("强制审核退款单完成");
            returnMap.put("message", returnArray);
            logUtil.trace(new DBLog(refundIds, "强制审核退款单", "系统退款单", "强制审核退款单完成，审核结果：" + returnArray.toJSONString()),logDao,currentUser.getFullName());
        } catch (Exception e) {
            logger.error(e.getMessage());
            returnMap = getFailedMap(e.getMessage());
            logUtil.trace(new DBLog(refundIds, "强制审核退款单", "系统退款单", "系统程序异常，请联系系统管理员"),logDao,currentUser.getFullName());
        }
        // 生成返回结果json串，null内容也需要返回
        returnMap.put("refundId", refundIds);
        return returnMap;
    }

    /**
     * cancelSysRefund:取消审核. <br/>
     *
     * @author zhanghao
     * @param refundIds
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/cancelAuthenSysRefund")
    @SystemControllerLog(module = "系统退款单", operation = "取消审核退款单", keyCode = "refundId")
    public Map<String, Object> cancelAuthenSysRefund(@RequestParam(value = "refundIds") String refundIds) {
        logger.info(String.format("系统调用取消审核：/sysRefundManager/cancelAuthenSysRefund/%s", refundIds));
        String[] refundIdArray = StringUtils.split(refundIds, ",");
        // 用于返回值的json对象
        Map<String, Object> returnMap = null;
        CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
        try {
            int result = sysRefundService.doCancelAppr(refundIdArray);
            if (result > 0) {
                returnMap = getSuccessMap("退款单已取消审核");
                logUtil.trace(new DBLog(refundIds, "取消审核退款单", "系统退款单", "取消审核完成"),logDao,currentUser.getFullName());
            } else if (0 == result) {
                returnMap = getFailedMap("退款单[" + refundIds + "]取消审核失败，请刷新后重试");
                logUtil.trace(new DBLog(refundIds, "取消审核退款单", "系统退款单", "没有可以取消审核的退款单"),logDao,currentUser.getFullName());
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            returnMap = getFailedMap(e.getMessage());
            logUtil.trace(new DBLog(refundIds, "取消审核退款单", "系统退款单", "系统程序异常，请联系系统管理员"),logDao,currentUser.getFullName());
        }
        // 生成返回结果json串，null内容也需要返回
        returnMap.put("refundId", refundIds);
        return returnMap;
    }

    /**
     * doRefund:执行退款. <br/>
     *
     * @author zhanghao
     * @param refundIds
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/doRefund")
    @SystemControllerLog(module = "系统退款单", operation = "执行退款", keyCode = "refundId")
    public Map<String, Object> doRefund(@RequestParam(value = "refundIds") String refundIds) {
        logger.info(String.format("系统调用执行退款：/sysRefundManager/doRefund/%s", refundIds));
        String[] refundIdArray = StringUtils.split(refundIds, ",");
        // 用于返回值的json对象
        Map<String, Object> returnMap = null;
        CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
        try {
            int result = sysRefundService.doRefund(refundIdArray);
            if (result > 0) {
                returnMap = getSuccessMap("退款完成");
                logUtil.trace(new DBLog(refundIds, "执行退款", "系统退款单", "退款完成"),logDao,currentUser.getFullName());
            } else if (0 == result) {
                returnMap = getFailedMap("退款单[" + refundIds + "]退款失败，请刷新后重试");
                logUtil.trace(new DBLog(refundIds, "执行退款", "系统退款单", "不存在可执行退款的退款单"),logDao,currentUser.getFullName());
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            returnMap = getFailedMap(e.getMessage());
            logUtil.trace(new DBLog(refundIds, "执行退款", "系统退款单", "系统程序异常，请联系系统管理员"),logDao,currentUser.getFullName());
        }
        // 生成返回结果json串，null内容也需要返回
        returnMap.put("refundId", refundIds);
        return returnMap;
    }

    /**
     * doRefund:执行退款校验. <br/>
     *
     * @author zhanghao
     * @param refundId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/doRefundValid")
    public Map<String, Object> doRefundValid(@RequestParam(value = "refundId") String refundId) {
        logger.info(String.format("系统调用执行退款：/sysRefundManager/doRefundValid/%s", refundId));
        // 用于返回值的json对象
        Map<String, Object> returnMap = null;
        CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
        try {
            String result = sysRefundService.doRefundValid(refundId);
            returnMap = getSuccessMap(result);
            logUtil.trace(new DBLog(refundId, "执行退款", "系统退款单", result),logDao,currentUser.getFullName());
        } catch (Exception e) {
            logger.error(e.getMessage());
            returnMap = getFailedMap(e.getMessage());
            logUtil.trace(new DBLog(refundId, "执行退款", "系统退款单", "系统程序异常，请联系系统管理员"),logDao,currentUser.getFullName());
        }
        // 生成返回结果json串，null内容也需要返回
        return returnMap;
    }

    /**
     * getSysRefundList:查询系统退款单. <br/>
     *
     * @author zhanghao
     * @param quickSearch
     *            快速查询字符串
     * @param start
     *            起始Index
     * @param length
     *            数据数
     * @param formJson
     *            高级查询表单数据
     * @param queryStatus
     *            列表状态
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/sysRefundList")
    public Map<String, Object> getSysRefundList(String quickSearch, @RequestParam(required = false, defaultValue = "0") int start,
            @RequestParam(required = false, defaultValue = "10") int length, String formJson, String queryStatus) throws Exception {
        logger.info("查询系统退款单：/sysRefundManager/sysRefundList");
        SysRefundVO queryParamVO = new SysRefundVO();
        if (quickSearch != null && StringUtils.isNotEmpty(quickSearch)) {
            quickSearch = URLDecoder.decode(quickSearch, "UTF-8");
            if (StringUtils.isNotEmpty(quickSearch)) {
                queryParamVO.setQuickSearch(quickSearch);
                ;
            }
        }
        if (formJson != null && StringUtils.isNotEmpty(formJson)) {
            formJson = URLDecoder.decode(formJson, "UTF-8");
            Map<String, String> mapItem = JSONObject.parseObject(formJson, Map.class);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            if (mapItem != null && !mapItem.isEmpty()) {
                if (StringUtils.isNotEmpty(mapItem.get("orderCode"))) {
                    queryParamVO.setQueryOrderCode(mapItem.get("orderCode"));
                }
                if (StringUtils.isNotEmpty(mapItem.get("shopId"))) {
                    queryParamVO.setShopId(mapItem.get("shopId"));
                }
                if (StringUtils.isNotEmpty(mapItem.get("dateType"))) {
                    queryParamVO.setQueryDateType(mapItem.get("dateType"));
                }
                if (StringUtils.isNotEmpty(mapItem.get("queryDateStart"))) {
                    queryParamVO.setQueryDateStart(sdf.parse(mapItem.get("queryDateStart")));
                }
                if (StringUtils.isNotEmpty(mapItem.get("queryDateEnd"))) {
                    queryParamVO.setQueryDateEnd(sdf.parse(mapItem.get("queryDateEnd")));
                }
                if (StringUtils.isNotEmpty(mapItem.get("ecItemCode"))) {
                    queryParamVO.setQueryEcItemCode(mapItem.get("ecItemCode"));
                }
                if (StringUtils.isNotEmpty(mapItem.get("ecSkuCode"))) {
                    queryParamVO.setQueryEcSkuCode(mapItem.get("ecSkuCode"));
                }
                if (StringUtils.isNotEmpty(mapItem.get("skuCode"))) {
                    queryParamVO.setQuerySkuCode(mapItem.get("skuCode"));
                }
                if (StringUtils.isNotEmpty(mapItem.get("returnDiff"))) {
                    queryParamVO.setReturnDiff(mapItem.get("returnDiff"));
                }
                if (StringUtils.isNotEmpty(mapItem.get("refundChannel"))) {
                    queryParamVO.setRefundChannel(mapItem.get("refundChannel"));
                }
            }

        }

        Map<String, String> replaceFieldsMap = new HashMap<String, String>();

        // 排序语句生成
        String orderStatement = getOrderString(ISysRefundDAO.class.getName(), "pageSelectSysRefundByCondition", replaceFieldsMap);
        if (StringUtils.isNotEmpty(orderStatement)) {
            queryParamVO.setOrderBy(orderStatement);
        }

        // 获取当前登录人
        CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
        if (currentUser == null) {
            return getFailedMap("查询当前登录人失败");
        }

        // 获取当前登录人所属项目
        String projectId = currentUser.getCurrentProject().getPrjId();
        if (StringUtils.isBlank(projectId)) {
            return getFailedMap("查询当前登录人所属项目失败");
        }
        queryParamVO.setPrjId(projectId);

        if (StringUtils.isNotEmpty(queryStatus)) {
            queryParamVO.setQueryStatus(queryStatus);
        }

        // 处理分页信息
        if (length == -1) {
            length = Integer.MAX_VALUE;
        }
        int page = start / length + 1;

        // 执行查询
        PageInfo<SysRefundVO> ruleVOList = sysRefundService.getSysRefundListByCondition(page, length, queryParamVO);

        Map<String, Object> returnMap = null;
        if (null != ruleVOList) {
            returnMap = getSuccessMap("查询系统退款单数据成功");
            returnMap.put(RECORDS_FILTERED, ruleVOList.getTotal());
            returnMap.put(RECORDS_TOTAL, ruleVOList.getTotal());
            returnMap.put(RETURN_DATA, ruleVOList.getList());
        } else {
            returnMap = getFailedMap("查询系统退款单数据失败");
        }
        logger.info("查询系统退款单调用结束");
        return returnMap;
    }

    /**
     * 通过订单ID获取退款单基本信息 wangxing add
     * 
     * @param orderId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getSysRefundListByOrderId")
    public Map<String, Object> getSysRefundListByOrderId(@RequestParam(value = "orderId") String orderId) {
        logger.info(String.format("系统调用通过订单ID获取系统退款单信息：/sysRefundManager/getSysRefundListByOrderId/%s", orderId));
        // 用于返回值的json对象
        Map<String, Object> returnMap = null;
        try {
            List<SysRefund> sysRefundList = sysRefundService.findSysRefundListByOrderId(orderId);
            if (sysRefundList.size() > 0) {
                returnMap = getSuccessMap("系统调用完成");
                returnMap.put(RETURN_DATA, sysRefundList);
            } else {
                returnMap = getFailedMap("系统调用完成,未获取到数据");
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            returnMap = getFailedMap(e.getMessage());
        }
        return returnMap;
    }

    /**
     * getSuccessMap:获取成功消息Map. <br/>
     *
     * @author zhanghao
     * @param message
     * @return
     * @since JDK 1.6
     */
    private Map<String, Object> getSuccessMap(String message) {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        returnMap.put(JSON_RESULT, SUCCESS);
        returnMap.put(JSON_MSG, message);
        return returnMap;
    };

    /**
     * getFailedMap:获取失败消息Map. <br/>
     *
     * @author zhanghao
     * @param message
     * @return
     * @since JDK 1.6
     */
    private Map<String, Object> getFailedMap(String message) {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        returnMap.put(JSON_RESULT, FAILED);
        returnMap.put(JSON_MSG, message);
        return returnMap;
    };
}
